﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Telerik.Web.UI;

public partial class Admin_Components_Member_RoleDetail : System.Web.UI.UserControl
{

    //DatabaseHelper DB = new DatabaseHelper();
    DataTable dt = new DataTable();
    static int FormState = -1; //trạng thái form ban đầu
    static int roleId = 0;
    String i_UserID;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                i_UserID = Session["UserName"].ToString();
                if (Session["Role"] == null)
                    FormState = 0;
                else
                    FormState = (int)Session["Role"];


                SetupForm();
                switch (FormState)
                {
                    case 0:
                        {
                            break;
                        }
                    default:
                        {
                            roleId = int.Parse( Session["Role_ID"].ToString());
                            LoadDatatoForm();
                            break;
                        }
                }
                Session.Remove("Role");
            }
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void SetupForm()
    {
        //Load dữ liệu cho các control khi vừa load form
        Utils.LoadDataToCombo(cboParentID, "Role_cbo_ParentID",DbType.Int32,2);
        
        cboParentID.SelectedIndex = 0;

        //Load dữ liệu cho các control khi StateForm = 1,2
        txtID.Text = ID;

        SetEnable();
    }

    protected void ClearForm()
    {
        cboParentID.SelectedIndex = 0;
        txtID.Text = "";
        txtRoleName.Text = "";
        txtRemark.Text = "";
        FormState = 0;
    }

    protected void SetEnable()
    {
        switch (FormState)
        {
            case 0://Thêm mới
                {
                    btnDelete.Enabled = false;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    btnDelete.CssClass = "btn btn-sm btn-warning";

                    txtID.Enabled = false;
                    break;
                }
            case 1://Sửa/Xóa
                {
                    btnDelete.Enabled = true;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    txtID.Enabled = false;
                    break;
                }
            default://Chỉ xem
                {
                    btnDelete.Visible = false;
                    btnGotoList.Visible = false;
                    btnNew.Visible = false;
                    btnSave.Visible = false;
                    break;
                }
        }
    }

    protected void LoadDatatoForm()
    {
        try
        {
            //DB.ClearParameter();

            //DbParameter paramID = DB.Parameter;
            //paramID.ParameterName = "ID";
            //paramID.DbType = DbType.Int32;
            //paramID.Value = ID;
            //DB.AddParameter(paramID);

            //dt = DB.ExecuteDataTable("Role_Load", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

            //if (dt.Rows.Count == 1)
            //{
            //    DataRow dr = dt.Rows[0];
            //    cboParentID.SelectedValue = dr["ParentID"].ToString();
            //    txtID.Text = dr["ID"].ToString();
            //    txtRemark.Text = dr["Remark"].ToString();
            //    txtRoleName.Text = dr["RoleName"].ToString();
            //    string IsSystemRole = dr["IsSystemRole"].ToString();
            //    if (IsSystemRole == "True")
            //    {
            //        radNo.Checked = false;
            //        radYes.Checked = true;
            //    }
            //    else
            //    {
            //        radNo.Checked = true;
            //        radYes.Checked = false;
            //    }
            //}


            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
            List<Role_LoadResult> listResult = dtx.Role_Load(roleId).ToList();
            if (listResult.Count == 1)
            {
                cboParentID.SelectedValue = listResult[0].ParentID.ToString();
                txtID.Text = listResult[0].ID.ToString();
                txtRemark.Text = listResult[0].Remark;
                txtRoleName.Text = listResult[0].RoleName;
                bool IsSystemRole = (bool)listResult[0].IsSystemRole;
                if (IsSystemRole)
                {
                    radNo.Checked = false;
                    radYes.Checked = true;
                }
                else
                {
                    radNo.Checked = true;
                    radYes.Checked = false;
                }
            }
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void SaveData()
    {
        try
        {
            if (txtID.Text == null || txtID.Text == "")
                FormState = 0;
            else
                FormState = 1;
            if (txtRoleName.Text == "")
            {
                txtRoleName.Focus();
               
               // lblResult.Text = "Tên chức danh không rỗng";
               // JavascriptUtil.LoadMessage(UpdatePanel1, false, "Tên chức danh không rỗng.");
                return;
            }
           
            //bỏ những ký tự đặc biệt, chống SQL Injection
            txtRoleName.Text = Utils.KillChars(txtRoleName.Text);
            txtRemark.Text = Utils.KillChars(txtRemark.Text);

            ////Add param cho store
            //DbParameter paramRoleName = DB.Parameter;
            //paramRoleName.ParameterName = "RoleName";
            //paramRoleName.DbType = DbType.String;
            //paramRoleName.Value = txtRoleName.Text;
            //DB.AddParameter(paramRoleName);

            //DbParameter paramRemark = DB.Parameter;
            //paramRemark.ParameterName = "Remark";
            //paramRemark.DbType = DbType.String;
            //paramRemark.Value = txtRemark.Text;
            //DB.AddParameter(paramRemark);

            //DbParameter paramIsSystemRole = DB.Parameter;
            //paramIsSystemRole.ParameterName = "IsSystemRole";
            //paramIsSystemRole.DbType = DbType.Boolean;
            //paramIsSystemRole.Value = radYes.Checked == true ? 1 : 0;
            //DB.AddParameter(paramIsSystemRole);

            //DbParameter paramParentID = DB.Parameter;
            //paramParentID.ParameterName = "ParentID";
            //paramParentID.DbType = DbType.Int32;
            //paramParentID.Value = cboParentID.SelectedValue;
            //DB.AddParameter(paramParentID);

            //DbParameter paramStatus = DB.Parameter;
            //paramStatus.ParameterName = "Status";
            //paramStatus.DbType = DbType.String;
            //paramStatus.Value = "A";
            //DB.AddParameter(paramStatus);

            //DbParameter paramByUser = DB.Parameter;
            //paramByUser.ParameterName = "ByUser";
            //paramByUser.DbType = DbType.String;
            //paramByUser.Value = i_UserID; //User đang thao tác
            //DB.AddParameter(paramByUser);

            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
            DBDataContext dtxRead = LINQUtil.GetDBReadOnly();
            if (FormState == 0)
            {
                //dt = DB.ExecuteDataTable("Role_Create", CommandType.StoredProcedure, ConnectionState.CloseOnExit);             
                dtx.Role_Create(txtRoleName.Text, txtRemark.Text, radYes.Checked == true ? true : false, int.Parse(cboParentID.SelectedValue.ToString()), ObjectStatus.Active, i_UserID);
                //Session["RoleIDA"] = DB.ExecuteScalar("Role_ID", CommandType.StoredProcedure, ConnectionState.CloseOnExit).ToString();              
                Role_IDResult idResult = dtxRead.Role_ID().Single();
                Session["RoleIDA"] = idResult.Column1;
                txtID.Text = Session["RoleIDA"].ToString();

               JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thêm mới thành công!");
                btnDelete.Enabled = true;
                btnDelete.CssClass = "btn btn-sm btn-warning";
            }
            else if (FormState == 1)
            {
                //DbParameter paramID = DB.Parameter;
                //paramID.ParameterName = "ID";
                //paramID.DbType = DbType.Int32;
                //paramID.Value = txtID.Text;
                //DB.AddParameter(paramID);
                //dt = DB.ExecuteDataTable("Role_Update", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

                dtx.Role_Update(int.Parse(txtID.Text), txtRoleName.Text, txtRemark.Text, radYes.Checked == true ? true : false, int.Parse(cboParentID.SelectedValue.ToString()), ObjectStatus.Active,i_UserID);

                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Cập nhật thành công!");

            }
        }
        catch (Exception ex)
        {
           JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công.");
        }
    }

    protected void DeleteData()
    {
       
        //DB.ClearParameter();

        ////Add param cho store
        //DbParameter paramCMCode = DB.Parameter;
        //paramCMCode.ParameterName = "ID";
        //paramCMCode.DbType = DbType.Int32;
        //paramCMCode.Value = txtID.Text;
        //DB.AddParameter(paramCMCode);

        //DbParameter paramByUser = DB.Parameter;
        //paramByUser.ParameterName = "ByUser";
        //paramByUser.DbType = DbType.String;
        //paramByUser.Value = i_UserID; //User đang thao tác
        //DB.AddParameter(paramByUser);

        try
        {
            //dt = DB.ExecuteDataTable("Role_Delete", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
           // dtx.Role_Delete(int.Parse(txtID.Text), i_UserID);
            dtx.Role_DeleteALL(int.Parse(txtID.Text), Session["UserName"].ToString());
          JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa thành công");
        }
        catch (Exception ex)
        {
           
            //lblResult.Text = "Thông báo lỗi: Xóa không thành công. Mã lỗi: Role - " + ex.Message;
           JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công.");
        }
    }

    protected Boolean CheckAllBeforeSave()
    {
        Boolean flag = true;
        if (txtRoleName.Text == "")
        {
        //    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Tên quyền không được rỗng");
            //lblResult.Text = "[Tên quyền] không được rỗng";
            flag = false;
        }
        return flag;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        
        try
        {
            SaveData();
            btnDelete.Focus();
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        
        try
        {
            DeleteData();
            ClearForm();
            SetEnable();
            btnNew.Focus();
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
       
        ClearForm();
        SetEnable();
        btnGotoList.Focus();
        cboParentID.Items.Clear();
        Utils.LoadDataToCombo(cboParentID, "Role_cbo_ParentID", DbType.Int32, 2);
    }

    protected void btnGotoList_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/RoleList");
    }
    protected void txtRoleName_TextChanged(object sender, EventArgs e)
    {
        txtRemark.Focus();
    }
    protected void cboParentID_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        txtRoleName.Focus();
    }
    protected void txtRemark_TextChanged(object sender, EventArgs e)
    {
        radYes.Focus();
    }
    protected void radYes_CheckedChanged(object sender, EventArgs e)
    {
        radNo.Focus();
    }
    protected void radNo_CheckedChanged(object sender, EventArgs e)
    {
        btnSave.Focus();
    }    
}